package com.kevin.data.batch.component;

import com.kevin.data.batch.configuration.BizJobListener;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.JobStepBuilder;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 嵌套处理
 */
@Component
public class NestedBatchComponent {

    @Resource
    private JobLauncher jobLauncher;

    @Resource
    private BizJobListener jobListener;

    @Resource
    private JobRepository jobRepository;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Bean("nestedJob")
    public Job nestedJob() {
        return new JobBuilder("nestedJob", jobRepository).start(childJobStep1()).next(childJobStep2()).listener(jobListener).build();
    }

    private Step childJobStep1() {
        return new JobStepBuilder(new StepBuilder("childJobStep1", jobRepository))
                .job(childJob1()).launcher(jobLauncher).allowStartIfComplete(true).build();
    }

    private Step childJobStep2() {
        return new JobStepBuilder(new StepBuilder("childJobStep2", jobRepository))
                .job(childJob2()).launcher(jobLauncher).allowStartIfComplete(true).build();
    }

    private Job childJob1() {
        return new JobBuilder("childJob1", jobRepository).start(childStep1()).build();
    }

    private Job childJob2() {
        return new JobBuilder("childJob2", jobRepository).start(childStep2()).build();
    }

    private Step childStep1() {
        return new StepBuilder("childStep1", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("childStep1 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

    private Step childStep2() {
        return new StepBuilder("childStep2", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("childStep2 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

}
